package com.ler.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ler.auth.entity.ClientDO;
import com.ler.auth.mapper.ClientMapper;
import com.ler.auth.service.ClientService;
import com.ler.yrmall.basic.Form;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Leron
 */
@Slf4j
@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, ClientDO> implements ClientService {

    @Override
    public IPage<ClientDO> find(Form request) {
        return this.page(request.getPage(),Wrappers.<ClientDO>lambdaQuery()
                .eq(StringUtils.isNotBlank(request.getKeyword()),ClientDO::getClientName,request.getKeyword()));
    }

    @Override
    public String saveClient(ClientDO request) {
        String password = RandomUtil.randomString(10);
        String clientId = genPasswd(password);
        request.setClientId(clientId);
        String secret = RandomUtil.randomString(10);
        log.info("{} - {}",clientId,password);
        request.setClientSecret(secret);
        this.save(request);
        return password;
    }

    @Override
    public String resetSecret(String clientId) {
        String password = RandomUtil.randomString(10);
        String secret = genPasswd(password);
        log.info("{} - {}",clientId,password);
        ClientDO client = new ClientDO();
        client.setClientId(clientId);
        client.setClientSecret(secret);
        this.updateById(client);
        return password;
    }

    private static String genPasswd(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
}
